#!/bin/bash

[ -z "${MYSQL_DATABASES}" ] && exit 1
PASSWORD=$1
if [ -z "${PASSWORD}" ];
then
  echo "create database need old password!"
  exit 1
fi
OLD_IFS="$IFS";IFS=",";DATABASES=(${MYSQL_DATABASES});IFS="$OLD_IFS"
SQL_FILE=${APP_OUTPUT_DIR}/databases_temp.sql
for DATABASE in "${DATABASES[@]}"
do
  #DB_INFO[0]数据库名称 DB_INFO[1]用户名 DB_INFO[2]密码
  OLD_IFS="$IFS";IFS=":";DB_INFO=(${DATABASE});IFS="$OLD_IFS"
  echo "CREATE DATABASE ${DB_INFO[0]} CHARACTER SET utf8;" >> ${SQL_FILE}
  if [ ${#DB_INFO[@]} -eq 3 ];
  then
    echo "CREATE USER '${DB_INFO[1]}'@'%' IDENTIFIED BY '${DB_INFO[2]}';" >> ${SQL_FILE}
    echo "grant all privileges on ${DB_INFO[0]}.* to '${DB_INFO[1]}'@'%';" >> ${SQL_FILE}
    echo "flush privileges;" >> ${SQL_FILE}
  fi
done
mysql -u root --password=${PASSWORD} --connect-expired-password < ${SQL_FILE}
! [ ${MYSQL_SAVE_SQL_TEMP} == YES ] && rm -rf ${SQL_FILE}

